/****************************************************************
 *  FileName: apply.c
 *  Author: Harsh and Maulik
 *  Description: With this file you can make apply function.
 *  Last Updated: 5th Sept. 2011
 ***************************************************************/	

#include "BDD.h"

/*Apply function will take two graphs as arguement and will return
 * a single graph.
 */

int fun(int value1, int value2, char op)
{
	if(op == '+')
	{
		if(value1 == 1 || value2 == 1)
			return 1;
		else if (value1 == 0 && value2 == 0)
			return 0;
		else
			return 3;
	}  else {
		if(value1 == 1 && value2 == 1)
			return 1;
		else if (value1 == 0 || value2 == 0)
			return 0;
		else
			return 3;
	}
}



graph *applyFunc(graph *g,graph *g1, graph *g2, int var1, int var2, char op)
{
	int i=0, j=0;
	int sizeG1 = graphSize(g1,var1);
	int sizeG2 = graphSize(g2,var2);
	char c[]="z";
	init(g);

	vertex *T[sizeG1][sizeG2];
	
	for(i = 0;i<sizeG1;i++)
	{
		for(j=0;j<sizeG2;j++)
			T[i][j] = NULL;
	}

	vertex *applyStep(vertex *v1, vertex *v2)
	{
		vertex *v, *vlow1, *vlow2, *vhigh1, *vhigh2;
		int value, index;
		
		v = T[(v1->id)-1][(v2->id)-1];
		if( v != NULL )
			return v;
		value = fun(v1->value, v2->value, op);
		v = (vertex *)insertVertex(value,0,c,0);
		T[(v1->id)-1][(v2->id)-1] = v;

		if (value != 3) //please note 3 stands for X
		{	v->index = 4;c[0]--;} //As total no of variables are 3 please please make it proper 
		else  {
			c[0]--;	
			
			if(v1->index < v2->index)
				v->index = v1->index;
			else
				v->index = v2->index;


			if (v1->index == v->index)
			{
				vlow1 = v1->low;
				vhigh1 = v1->high;
			} else {
				vlow1 = v1;
				vhigh1 = v1;
			}

			if (v2->index == v->index)
			{
				vlow2 = v2 ->low;
				vhigh2 = v2 -> high;
			} else  {
				vlow2 = v2;
				vhigh2 = v2;
			}
			v->low =  applyStep(vlow1,vlow2);
			v->high = applyStep(vhigh1,vhigh2);
			
		}
		
		return v;


	}



	(g->root) = applyStep((g1->root),(g2->root));



	
	reduction(g,4);  
	return g;
}




